require("dotenv").config(); // 读取 .env 文件
const express = require('express');
const cookieParser = require('cookie-parser');
//const formidable = require('express-formidable');
const formidable = require('formidable');
const { createProxyMiddleware } = require('http-proxy-middleware');
const cors = require('cors');
const path = require('path');

const fileRoutes = require('./routes/fileRoutes');
const serviceRoutes = require('./routes/serviceRoutes');
const { authRouter, authenticate } = require("./routes/authRoutes");
const fs = require("fs");

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件
app.use(cors()); // 允许跨域
app.use(cookieParser());
//app.use(formidable({ multiples: true }));
app.use(express.json());
app.use(express.static('api')); // 允许访问上传的文件
app.use(express.static('public'));  // 允许访问前端构建文件
// **通用请求解析中间件**
app.use((req, res, next) => {
    const contentType = req.headers['content-type'];

    if (contentType && contentType.includes('multipart/form-data')) {
        // 处理 multipart/form-data（文件上传）
        const form = new formidable.IncomingForm({ multiples: true, keepExtensions: true });

        form.parse(req, (err, fields, files) => {
            if (err) {
                return res.status(500).json({ error: 'Form parsing error' });
            }
            req.body = fields;  // 把解析的字段放到 req.body
            req.files = files;  // 把文件放到 req.files
            next();
        });
    } else {
        // 默认继续处理 JSON
        next();
    }
});

// 代理配置
const proxyTable = {
    '/api/proxy': 'https://jsonplaceholder.typicode.com'
};
Object.keys(proxyTable).forEach(context => {
    app.use(context, createProxyMiddleware({
        target: proxyTable[context],
        changeOrigin: true,
        pathRewrite: { [`^${context}`]: '' }
    }));
});

// 用户认证路由
app.use("/api/auth", authRouter);

// 受保护的 API（需要登录）
app.use("/api/fileManage", authenticate, fileRoutes);

// API 路由
app.use('/api/services', serviceRoutes);

// Vue 前端页面
app.get("/", (req, res) => {
    res.sendFile(path.join(__dirname, 'index.html'));
});



// 服务器启动
app.listen(PORT, () => {
    console.log(`Mock Server 运行在: http://localhost:${PORT}`);
});
